<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: Filter.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

class Zimm_Model_DbTable_Instruction_Filter extends Zimm_Model_DbTable_Instruction_Abstract
{
    /**
     * Apply an image filter.
     *
     * @param resource $image GD resource
     * @param string $savePath Target save path
     * @param array $params Instruction arguments
     * @return boolean Indicates if image was altered
     */
    protected function _process(&$image, $savePath, $params)
    {
        static $lut = array(
            'NEGATE'=>IMG_FILTER_NEGATE,
            'GRAYSCALE'=>IMG_FILTER_GRAYSCALE,
            'BRIGHTNESS'=>IMG_FILTER_BRIGHTNESS,
            'CONTRAST'=>IMG_FILTER_CONTRAST,
            'COLORIZE'=>IMG_FILTER_COLORIZE,
            'EDGEDETECT'=>IMG_FILTER_EDGEDETECT,
            'EMBOSS'=>IMG_FILTER_EMBOSS,
            'GAUSSIAN_BLUR'=>IMG_FILTER_GAUSSIAN_BLUR,
            'SELECTIVE_BLUR'=>IMG_FILTER_SELECTIVE_BLUR,
            'MEAN_REMOVAL'=>IMG_FILTER_MEAN_REMOVAL,
            'SMOOTH'=>IMG_FILTER_SMOOTH,
            'PIXELATE'=>IMG_FILTER_PIXELATE,
        );

        if (isset($params['args']) && !empty($params['args'])) {
            $args = $params['args'];
            if (isset($args[0]) && isset($lut[$x = strtoupper($args[0])])) {
                $args[0] = $lut[$x];
            }
            foreach ($args as $k=>$v) {
                $args[$k] = (int)$v;
            }

            array_unshift($args, $image);
            try {
                call_user_func_array('imagefilter', $args);
                return true;
            } catch (Exception $e) {

            }
        }
        return false;
    }
}